<?php

namespace app\common\model\base;

use app\common\model\BaseModel;
use helper\FormBuilder;

class ConfigModel extends BaseModel {

    protected $table = 'config';

    /**
     * 刷新缓存
     * @return array
     */
    public function refreshCache(){
        $webConfig = $this->column('config_value','config_key');
        cache('web_config',$webConfig);
        return $webConfig;
    }

    /**
     * 添加
     * @param $data
     * @return ConfigModel|\think\Model
     * @throws \Exception
     */
    public function add($data){
        $info = $this->where('config_key',$data['config_key'])->find();
        if($info) exception('已存在该字段标识');
        $info = self::create($data);
        $this->refreshCache();
        return $info;
    }

    /**
     * 编辑
     * @param $data
     * @return ConfigModel
     */
    public function edit($data){
        $info = self::update($data);
        $this->refreshCache();
        return $info;
    }

    /**
     * 删除
     * @param $id
     * @throws \Exception
     */
    public function del($id){
        $this->where('id',$id)->delete();
        $this->refreshCache();
    }

    /**
     * 获取表单数据
     * @param string $group
     * @return array
     * @throws \Exception
     */
    public function getForm($group='site'){
        $list = $this->where('config_group',$group)->order('show_order asc')->select()->toArray();
        foreach($list as $k=>$v){
            $fun = $v['config_type'];
            $options = empty($v['config_set']) ? [] : json_decode(($v['config_set']),true);
            $form = FormBuilder::$fun("config[{$v['config_key']}]",$v['config_value'],$options);
            $list[$k]['form'] = $form;
        }
        return $list;
    }
}